package com.hpq.user.service.impl;

import com.hpq.common.utils.AssertUtil;
import com.hpq.user.dao.UserEmojiDAO;
import com.hpq.user.domain.model.UserEmoji;
import com.hpq.common.domain.vo.response.IdRespVO;
import com.hpq.user.domain.vo.request.user.UserEmojiReq;
import com.hpq.user.domain.vo.response.user.UserEmojiResp;
import com.hpq.user.service.UserEmojiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserEmojiServiceImpl implements UserEmojiService {
    @Autowired
    private UserEmojiDAO userEmojiDao;


    @Override
    public IdRespVO insert(UserEmojiReq req, Long uid) {
        int count  = userEmojiDao.countByUid(uid);
        AssertUtil.isTrue(count >= 30, "最多添加30个表情");
        // 校验表情是否已存在
        int existEmojis = userEmojiDao.countByUrl(req.getExpressionUrl(), uid);
        AssertUtil.isTrue(existEmojis > 0, "表情已存在");
        UserEmoji insert =UserEmoji.builder().expressionUrl(req.getExpressionUrl()).uid(uid).build();
        userEmojiDao.save(insert);
        return IdRespVO.id(insert.getId());
    }

    @Override
    public List<UserEmojiResp> list(Long uid) {
        return userEmojiDao.listByUid(uid).stream()
                .map( a -> UserEmojiResp.builder().id(a.getId()).expressionUrl(a.getExpressionUrl()).build())
                .collect(Collectors.toList());
    }

    @Override
    public void delete(long id, Long uid) {
        UserEmoji userEmoji = userEmojiDao.getById(id);
        AssertUtil.isEmpty(userEmoji, "表情不存在");
        AssertUtil.isNotEqual(userEmoji.getUid(), uid, "你不能删别人的表情");
        userEmojiDao.removeById(id);
    }


}
